﻿using DevExpress.Utils.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using XCI.Core;
using XCI.Helper;

namespace XCI.Windows
{
    public partial class FrmExportSelectFields : BaseForm
    {
        private readonly List<Simple> allFieldsList = new List<Simple>();
        private readonly List<Simple> selectedFieldsList = new List<Simple>();
        private readonly string[] fields;
        private readonly bool autoAddAll;

        public FrmExportSelectFields(string[] fields, bool autoAddAll)
        {
            InitializeComponent();
            this.fields = fields;
            this.autoAddAll = autoAddAll;
            gridAll.DataSource = allFieldsList;
            gridSelected.DataSource = selectedFieldsList;
        }

        /// <summary>
        /// 获取选中的字段数组
        /// </summary>
        public string[] GetSelectedFields()
        {
            return selectedFieldsList.Select(p => p.Name).ToArray();
        }

        private void InitForm()
        {
            gridViewAll.Appearance.Row.BackColor = gridViewAll.Appearance.Empty.BackColor = this.BackColor;
            gridViewSelected.Appearance.Row.BackColor = gridViewSelected.Appearance.Empty.BackColor = this.BackColor;

            if (fields == null || fields.Length == 0)
            {
                MessageBoxHelper.ShowWarn("请设置导出的列集合");
                return;
            }

            InitFields();
            SetButtonStatus();
        }

        private void InitFields()
        {
            allFieldsList.Clear();
            selectedFieldsList.Clear();

            foreach (var item in fields)
            {
                allFieldsList.Add(new Simple { Name = item });
            }

            if (autoAddAll)
            {
                allFieldsList.ForEach(p => selectedFieldsList.Add(p));
                allFieldsList.Clear();
            }

            gridAll.RefreshDataSource();
            gridSelected.RefreshDataSource();
        }

        private void SetButtonStatus()
        {
            var selectedIndexs = gridViewSelected.GetSelectedRows();
            var allIndexs = gridViewAll.GetSelectedRows();

            btnToSelected.Enabled = allFieldsList.Count > 0 && allIndexs.Length > 0;//往右移动按钮
            btnToAll.Enabled = selectedFieldsList.Count > 0 && selectedIndexs.Length > 0;//往左移动按钮

            btnToUp.Enabled = IsAllowUp();
            btnToDown.Enabled = IsAllowDown();
        }

        private void GridToGridMove(GridViewPlus from, GridViewPlus to)
        {
            var rows = from.GetSelectedRows();
            if (rows.Length <= 0) return;

            var fromDataSource = (List<Simple>)from.DataSource;
            var toDataSource = (List<Simple>)to.DataSource;

            var index = rows.Last();
            rows.ForEach(dataIndex => toDataSource.Add(fromDataSource[dataIndex]));
            from.DeleteSelectedRows();

            if (index > (from.DataRowCount - 1))
            {
                index = from.DataRowCount - 1;
            }
            from.SelectRow(index);

            from.GridControl.RefreshDataSource();
            to.GridControl.RefreshDataSource();
        }

        private void ToSelected()
        {
            GridToGridMove(gridViewAll, gridViewSelected);
        }

        private void ToAll()
        {
            GridToGridMove(gridViewSelected, gridViewAll);
        }

        private bool IsAllowUp()
        {
            var rows = gridViewSelected.GetSelectedRows();
            if (rows.Length <= 0) return false;

            for (int i = 0; i < rows.Length; i++)
            {
                var dataIndex = rows[i];
                if (dataIndex == 0) continue;
                if (dataIndex == i) continue;

                return true;
            }

            return false;
        }

        private void SelectedUp()
        {
            var rows = gridViewSelected.GetSelectedRows();
            if (rows.Length <= 0) return;

            for (int i = 0; i < rows.Length; i++)
            {
                var dataIndex = rows[i];
                if (dataIndex == 0) continue;
                if (dataIndex == i) continue;

                var newIndex = dataIndex - 1;
                var data = selectedFieldsList[dataIndex];
                selectedFieldsList.RemoveAt(dataIndex);
                selectedFieldsList.Insert(newIndex, data);
                gridViewSelected.UnselectRow(dataIndex);
                gridViewSelected.SelectRow(newIndex);
            }
            gridSelected.RefreshDataSource();
        }

        private bool IsAllowDown()
        {
            var rows = gridViewSelected.GetSelectedRows();
            if (rows.Length <= 0) return false;

            Array.Reverse(rows);
            var total = gridViewSelected.DataRowCount - 1;
            for (int i = 0; i < rows.Length; i++)
            {
                var dataIndex = rows[i];
                var chaIndex = total - dataIndex;
                if (dataIndex == total) continue;
                if (chaIndex == i) continue;

                return true;
            }

            return false;
        }

        private void SelectedDown()
        {
            var rows = gridViewSelected.GetSelectedRows();
            if (rows.Length <= 0) return;

            Array.Reverse(rows);
            var total = gridViewSelected.DataRowCount - 1;
            for (int i = 0; i < rows.Length; i++)
            {
                var dataIndex = rows[i];
                var chaIndex = total - dataIndex;
                if (dataIndex == total) continue;
                if (chaIndex == i) continue;

                var newIndex = dataIndex + 1;
                var data = selectedFieldsList[dataIndex];
                selectedFieldsList.RemoveAt(dataIndex);
                selectedFieldsList.Insert(newIndex, data);
                gridViewSelected.UnselectRow(dataIndex);
                gridViewSelected.SelectRow(newIndex);
            }
            gridSelected.RefreshDataSource();
        }

        private void FrmExportSelectFields_Load(object sender, EventArgs e)
        {
            InitForm();
        }

        private void BtnOk_Click(object sender, EventArgs e)
        {
            if (selectedFieldsList.Count == 0)
            {
                MessageBoxHelper.ShowWarn("请选择需要导出的列");
                return;
            }
            DialogOk();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            if (MessageBoxHelper.ShowMessageYesNo("确定要重置为默认值吗?") != System.Windows.Forms.DialogResult.Yes)
            {
                return;
            }

            InitFields();
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            DialogCancel();
        }

        private void btnToSelected_Click(object sender, EventArgs e)
        {
            ToSelected();
        }

        private void btnToAll_Click(object sender, EventArgs e)
        {
            ToAll();
        }

        private void btnToUp_Click(object sender, EventArgs e)
        {
            SelectedUp();
        }

        private void btnToDown_Click(object sender, EventArgs e)
        {
            SelectedDown();
        }

        private void gridViewAll_DoubleClick(object sender, EventArgs e)
        {
            ToSelected();
        }

        private void gridViewAll_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            SetButtonStatus();
        }

        private void gridViewSelected_DoubleClick(object sender, EventArgs e)
        {
            ToAll();
        }

        private void gridViewSelected_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            SetButtonStatus();
        }
    }
}